layui.define(function(exports) {
    var $ = layui.$,
    admin = layui.admin,
    setter = layui.setter,
    laytpl = layui.laytpl,
    form = layui.form,
    hot = layui.hot;
    var params = {};

    function initProductList() {
      // 初始化表单
      if (sessionStorage.category === 'CHANNEL' || sessionStorage.category === 'CHANNEL_SUB_ACC') {
        params = {
          isMall: 1
        };
      } else {
        params = {
          isJhzb: 1
        };
      }

      form.render(null, 'LAY_wisdom_product_search_form');

      // 表单提交
      form.on('submit(LAY_wisdom_product_search_btn)', function (data) {
        var field = data.field;
        params = $.extend(true, params, field);
        generateProductList(params);

        return false;
      });

      generateProductList(params);
    }

    function initEvents () {
      $('.LAY_hot_add').off('click').on('click', function () {
        var array = [];
        var name = $(this).data('name');
        var code = $(this).data('code');
        var object = {
          productCode: code,
          productName: name
        };
        array.push(object);

        hot.add(array);
      });

      $('.LAY_hot_batch_add').off('click').on('click', function () {
        var array = [];

        $('.LAY_wisdom_product_list_checkbox input:checked').each(function () {
          var name = $(this).data('name');
          var code = $(this).data('code');
          var object = {
            productCode: code,
            productName: name
          };
          
          array.push(object);
        });

        
        hot.add(array);
      });
    };

    // 产品列表
    function generateProductList(params) {
      admin.req({
        url: setter.url + '/product/getProductListMall',
        type: 'GET',
        data: params,
        done: function (res) {
          var data = res.data || [];

          renderData(data, function() {
            form.render(null, 'LAY_wisdom_product_list_form');
            initEvents();
          });
        }
      })
    }

    // 渲染数据
    function renderData(data, callback) { 
      var getTpl = $('#LAY_wisdom_product_list_tpl').html();

      if (!getTpl) {
        return;
      }

      laytpl(getTpl).render(data, function(html){
        $('#LAY_wisdom_product_list_view').html(html);

        if (typeof(callback) === 'function') {
          callback();
        }
      });
    }

    exports('hotProductLibrary', {
      init: initProductList,
      refresh: function () {
        generateProductList(params);
      }
    });
});